﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace ValidationFramework.WPF
{
	/// <summary>
	/// A <see cref="IValueConverter"/> for converting between <see cref="bool"/>s and <see cref="Enum"/>s.
	/// </summary>
#if (!SILVERLIGHT)
	[ValueConversion(typeof(bool), typeof(object))]
#endif
	public class EnumValueConverter : IValueConverter
	{
        /// <inheritdoc />
		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
		    if (targetType != typeof (bool) && targetType != typeof (bool?))
		    {
		        throw new ArgumentException("Type must be a bool", "targetType");
		    }
		    if (value.ToString() == (string)parameter)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

        /// <inheritdoc />
		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var enumType = Nullable.GetUnderlyingType(targetType);
			if (enumType == null)
			{
				enumType = targetType;
			}
			return Enum.Parse(enumType, (string) parameter, true);
		}
	}
}
